package com.example.product.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class ProductController {
    private static final Logger log = LoggerFactory.getLogger(ProductController.class);
    
    // 模拟商品库存（实际应操作数据库）
    private Map<String, Integer> stockMap = new HashMap<>();
    {
        stockMap.put("1001", 10); // 商品ID=1001，库存10
    }

    // 扣减库存接口
    @PostMapping("/product/deduct")
    public String deductStock(@RequestParam String productId, @RequestParam int count) {
        log.info("收到扣减库存请求 - 商品ID: {}, 数量: {}", productId, count);
        
        try {
            int stock = stockMap.getOrDefault(productId, 0);
            log.info("当前库存: {}", stock);
            
            if (stock < count) {
                log.warn("库存不足 - 当前库存: {}, 请求数量: {}", stock, count);
                return "库存不足";
            }
            
            stockMap.put(productId, stock - count);
            String result = "库存扣减成功，剩余库存：" + (stock - count);
            log.info(result);
            return result;
            
        } catch (Exception e) {
            log.error("扣减库存时发生错误", e);
            return "处理请求时发生错误：" + e.getMessage();
        }
    }
} 